package com.example.shopping.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.shopping.pojo.Commodity;
import com.example.shopping.service.CommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/admin")
public class CommodityCon {
    @Autowired
    private CommodityService commodityService;


    /**
     *  在前端传入的实体类的基础上
     *  修改img：虚拟路径
     *  修改flag：0未售出
     * @param commodity 实体类
     * @param multipartFile 图片流
     * @return
     * @throws IOException
     */
    @PostMapping("/insCommodity")
    @ResponseBody
    public String insCommodity(Commodity commodity, MultipartFile multipartFile) throws IOException {
        //获取输入流
        InputStream inputStream = multipartFile.getInputStream();

        //保存路径
        String uuid=UUID.randomUUID().toString();
        String url="C:\\commodity\\"+ uuid +".png";
        File target = new File(url);
        //获取输出流
        FileOutputStream fos = new FileOutputStream(target);
        //获取包装类
        BufferedInputStream bis = new BufferedInputStream(inputStream);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        //写文件
        int ch = 0;
        while ((ch = bis.read()) != -1) {
            bos.write(ch);
        }
        // 关流
        bos.close();
        bis.close();

        //编辑虚拟路径
        commodity.setImg("/commodity/"+uuid+".png");
        //编辑推荐状态
        commodity.setRecommend(0);
        commodityService.save(commodity);
        return "成功";
    }

    @GetMapping("/commodityList")
    @ResponseBody
    public List<Commodity> commodityList(){
        return commodityService.list();
    }

    @DeleteMapping("/removeCommentById/{id}")
    @ResponseBody
    public void removeCommentById(@PathVariable Integer id){
        commodityService.removeById(id);
    }

    @GetMapping("/changeRecommend/{commodityId}/{recommend}")
    @ResponseBody
    public void changeRecommend(@PathVariable Integer commodityId,@PathVariable Integer recommend){
        UpdateWrapper<Commodity> commodityUpdateWrapper = new UpdateWrapper<>();
        commodityUpdateWrapper.set("recommend",recommend).eq("id",commodityId);
        commodityService.update(commodityUpdateWrapper);
    }
}
